package lumis.service.user;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.Source;
import lumis.portal.PortalException;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.user.UserConfig;
import lumis.service.group.DomainScopeFilter;
import lumis.util.XmlUtil;

/**
 * Persists the user information.
 *
 * @version $Revision: 10825 $ $Date: 2009-08-04 12:36:40 -0300 (Tue, 04 Aug 2009) $
 * @since 5.0.0
 */
public class UserProcessActionHandler extends ProcessActionHandler<Source<?>>
{
	public static final String USER_ADD = "lum_userAdd";
	
	public void processAction() throws PortalException
	{
		String actionType = XmlUtil.readAttributeString("actionType", processActionNode);
		
		if (actionType == null)
			actionType = UserProcessActionHandler.USER_ADD;

		if (actionType.equals(UserProcessActionHandler.USER_ADD))
			processAddAction();
	}
	
	private void processAddAction() throws PortalException
	{
		String password = getParameter("password", String.class); 
		String confirmPassword = getParameter("confirmPassword", String.class); 
		
		if ((password != null && !password.equals(confirmPassword)) ||
				(password == null && confirmPassword != null))
			throw new PortalException("STR_PASSWORD_DOES_NOT_MATCH", douiContext.getRequest().getServiceConfig().getResource());
		
		// TODO validate other password constraints like length and complexity
		String login = getParameter("login", String.class); 
		String firstName = getParameter("firstName", String.class); 
		String middleName = getParameter("middleName", String.class); 
		String lastName = getParameter("lastName", String.class); 
		String email = getParameter("email", String.class); 
		Boolean disabled = getParameter("disabled", Boolean.class); 
		Boolean multiSession = getParameter("multiSession", Boolean.class); 
		
		// Gets and converts if necessary the domain channelId
		String serviceInstanceId = douiContext.getRequest().getServiceInstanceConfig().getId();
		String channelId = ManagerFactory.getServiceInstanceManager().getCustomProperty(sessionConfig, serviceInstanceId, DomainScopeFilter.DOMAIN_CUSTOM_PROPERTY_NAME, transaction);
		
		// if the domain is global, the user will be global. Put null in channelId
		if(DomainScopeFilter.GLOBAL_DOMAIN_VALUE.equals(channelId))
			channelId = null;
		
		// create user to be added
		UserConfig user = new UserConfig();
		user.setLogin(login);
		user.setFirstName(firstName);
		user.setMiddleName(middleName);
		user.setLastName(lastName);
		user.setEmail(email);		
		if("".equals(password))
			password = null;
		user.setPassword(password);
		user.setDisabled(disabled != null && disabled.booleanValue());
		user.setMultiSession(multiSession != null && multiSession.booleanValue());		
		user.setChannelId(channelId);
		
		// add user
		ManagerFactory.getUserManager().add(sessionConfig, user, transaction);

		addDefaultResponse();
	}
}
